<?php
/* $Id: login.php 74 2011-02-27 16:21:15Z jim2212001@gmail.com $ */
require_once 'config.php';
$thirdProvider = array('Google','Facebook','Yahoo');
$openidProvider = array('Google','Yahoo');
$openidIdentity = array(
	'Google' => 'https://www.google.com/accounts/o8/id',
	'Yahoo' => 'yahoo.com'
);
if(isset($_GET['type'])){
	if($_GET['type']=='native'){
	    $username = $db->real_escape_string($_POST['username']);
		$where = '`username`=\''.$username.'\'';
	  	if(($res = $db->query('SELECT * FROM `account` WHERE '.$where.' LIMIT 1')) === false || $db->affected_rows==0){
			errMsg(MSG_LOGIN_FAIL);
		}else{
			$row = $res->fetch_assoc();
			if(SaltMd5::Validate($_POST['password'],$row['password'])){
				$id = $row['id'];
				$perm = $row['perm'];
				$nickname = $row['name'];
				$account = $row['username'];
				$provider = 'native';
			}else{
				errMsg(MSG_LOGIN_FAIL);
			}
		}
	}else if($_GET['type']=='thirdParty'){
		try{
			/* (OpenID) */
			if(in_array($_GET['provider'],$openidProvider)){
			    require_once 'LightOpenID.class.php';
				$openid = new LightOpenID;
				if(!$openid->mode){
					$openid->identity = $openidIdentity[$_GET['provider']];
					$openid->required = array('contact/email');
					header('Location: '.$openid->authUrl());
					exit;
				}elseif($openid->mode == 'cancel'){
					errMsg(MSG_LOGIN_CANCEL);
				}elseif(!$openid->validate()){
					errMsg(MSG_LOGIN_FAIL);
				}else{
					$attr = $openid->getAttributes();
					$emailSeg=explode('@', $attr['contact/email']);
					$nickname = $emailSeg[0];
					$account = $attr['contact/email'];
					$provider = $_GET['provider'];
				}
			}
		} catch(ErrorException $e) {
			errMsg ('OpenID fail:'.$e->getMessage(),1);
		}
		/* Facebook(OAuth) */
		if($_GET['provider']=='Facebook'){
			$my_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'].'?type=thirdParty&provider=Facebook&fb';
			if(isset($_GET['fb'])){
				if(isset($_GET['error'])){
					errMsg(MSG_LOGIN_DEFAULT);
				}elseif(isset($_GET['code'])){
					$token_url='https://graph.facebook.com/oauth/access_token'.
						'?client_id='.FB_ID.
						'&redirect_uri='.urlencode($my_url).
						'&client_secret='.FB_SECRET.
						'&code='.$_GET['code'];
					$access_token = file_get_contents($token_url);
					$graph_url = 'https://graph.facebook.com/me?'.$access_token;
					$user = json_decode(file_get_contents($graph_url));
					$nickname = $user->name;
					$account = $user->id;
					$provider=$_GET['provider'];
				}
			}else{
				header('Location: https://www.facebook.com/dialog/oauth'.
				  '?client_id='.FB_ID.
				  '&redirect_uri='.urlencode($my_url));
			}
		}
		/* retriving native account */
		if(isset($provider) && in_array($provider,$thirdProvider)){
			$fieldPro = 'id'.$provider;
			$where = '`'.$fieldPro.'`=\''.$account.'\'';
			if(($res = $db->query('SELECT `id`,`username`,`name`,`perm` FROM `account` WHERE '.$where.' LIMIT 1'))===false){
				exit('MySQL Error');
			}
			if($row = $res->fetch_assoc()){
				$id = $row['id'];
				$perm = $row['perm'];
				$nickname = $row['name'];
				if(isset($row['username']) && strlen($row['username'])){
					$account = $row['username'];
					$provider = 'native';
				}
			}else{
				$perm = PERM_FOLLOWER;
				$db->query('INSERT INTO `account` (`name`,`'.$fieldPro.'`,`perm`) VALUES (\''.$nickname.'\',\''.$account.'\',\''.$perm.'\')',1);
				$id = $db->insert_id;
			}
		}
	}
	if(!hasErr()){
		$db->query('UPDATE `account` SET `ip`=\''.$_SERVER['REMOTE_ADDR'].'\' WHERE '.$where.' LIMIT 1');
		$_SESSION['id']=$id;
		$_SESSION['login']=$account;
		$_SESSION['nickname']=$nickname;
		$_SESSION['provider']=$provider;
		$_SESSION['perm']=$perm;
		$tpl->assign('nickname',$nickname);
		$tpl->assign('provider',$provider);
		infoMsg(MSG_LOGIN_SUCCESS);
	}
} elseif(isset($_GET['action'])){
	if(isset($_SESSION['login']) && $_GET['action']=='logout'){
		infoMsg(MSG_LOGIN_LOGOUT);
		unset($_SESSION['login']);
	}
}

$tpl->assign('thirdParty',$thirdProvider);
$tpl->display('login.htm');
?>
